#!/usr/bin/env node

import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { createInterface } from "readline";
import { spawn } from "child_process";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// SunAdmin Logo
const logo = `
  ______                     ___         _           _        
 / _____)                   (___)       | |         (_)       
( (____    _   _   ____    /_____\\    __| |  ____    _   ____  
 \\____ \\  | | | | |  _ \\  |  ___  |  / _  | |    \\  | | |  _ \\ 
 _____) ) | |_| | | | | | | |   | | ( (_| | | | | | | | | | | |
(______/  |____/  |_| |_| |_|   |_|  \\____| |_|_|_| |_| |_| |_|
`;

function copyTemplate(templateDir, targetDir) {
    if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true });
    }

    const files = fs.readdirSync(templateDir);

    for (const file of files) {
        const templatePath = path.join(templateDir, file);
        const targetPath = path.join(targetDir, file);

        if (fs.statSync(templatePath).isDirectory()) {
            copyTemplate(templatePath, targetPath);
        } else {
            fs.copyFileSync(templatePath, targetPath);
        }
    }
}

// 询问用户是否安装依赖
function askInstallDependencies() {
    return new Promise((resolve) => {
        const rl = createInterface({
            input: process.stdin,
            output: process.stdout,
        });

        rl.question("📦 是否立即安装依赖？(Y/n): ", (answer) => {
            rl.close();
            const normalizedAnswer = answer.trim().toLowerCase();
            // 默认为 yes，只有明确输入 n/no 才不安装
            resolve(normalizedAnswer !== "n" && normalizedAnswer !== "no");
        });
    });
}

// 执行 npm install
function installDependencies(projectDir, projectName) {
    return new Promise((resolve, reject) => {
        console.log(`\n🔄 正在安装依赖...`);

        const npmProcess = spawn("npm", ["install"], {
            cwd: projectDir,
            stdio: "inherit", // 让用户看到安装过程
            shell: true,
        });

        npmProcess.on("close", (code) => {
            if (code === 0) {
                console.log(`\n✅ 依赖安装完成！`);
                console.log(`\n🚀 现在你可以启动开发服务器：`);
                console.log(`   cd ${projectName}`);
                console.log(`   npm run dev`);
                resolve();
            } else {
                console.log(`\n⚠️  依赖安装失败，你可以手动安装：`);
                console.log(`   cd ${projectName}`);
                console.log(`   npm install`);
                resolve(); // 不reject，让程序正常结束
            }
        });

        npmProcess.on("error", (error) => {
            console.log(`\n⚠️  无法执行 npm install：${error.message}`);
            console.log(`   请手动安装依赖：`);
            console.log(`   cd ${projectName}`);
            console.log(`   npm install`);
            resolve(); // 不reject，让程序正常结束
        });
    });
}

async function main() {
    // 显示 SunAdmin Logo
    console.log(logo);
    console.log("🎉 欢迎使用 SunAdmin 脚手架工具！\n");

    const args = process.argv.slice(2);
    const projectName = args[0] || "my-sunadmin-app";

    const targetDir = path.resolve(process.cwd(), projectName);
    const templateDir = path.join(__dirname, "template");

    if (fs.existsSync(targetDir)) {
        console.error(`❌ 目录 ${projectName} 已存在！`);
        process.exit(1);
    }

    console.log(`🚀 正在创建 SunAdmin 项目: ${projectName}`);

    try {
        copyTemplate(templateDir, targetDir);

        // 更新 package.json 中的项目名称
        const packageJsonPath = path.join(targetDir, "package.json");
        if (fs.existsSync(packageJsonPath)) {
            const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
            packageJson.name = projectName;
            fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
        }
        // 询问是否安装依赖
        const shouldInstall = await askInstallDependencies();

        if (shouldInstall) {
            await installDependencies(targetDir, projectName);
        } else {
            console.log(`\n✅ 项目创建完毕, 请手动安装依赖, 并启动开发服务器:`);
            console.log(`\n📂 进入项目目录:`);
            console.log(`   cd ${projectName}`);
            console.log(`\n📦 安装依赖:`);
            console.log(`   npm install`);
            console.log(`\n🚀 启动开发服务器:`);
            console.log(`   npm run dev`);
        }
    } catch (error) {
        console.error("❌ 创建项目失败:", error.message);
        process.exit(1);
    }
}

main();
